package name.cyrax.red.jpv.impl.adapters;

import name.cyrax.red.jpv.api.adapters.CalculationContext;
import name.cyrax.red.jpv.api.adapters.LongAdapter;
import name.cyrax.red.jpv.api.adapters.NumericAdapter;
import name.cyrax.red.jpv.api.adapters.PrepareAdapter;
import name.cyrax.red.jpv.api.funcs.FunctorInstance;
import name.cyrax.red.jpv.api.funcs.info.ValueType;
import name.cyrax.red.jpv.impl.funcs.DefaultFunctorInstances;

public class CachedLongImpl extends LongImpl
{
	private final LongAdapter origin;
	private long[] cacheValues;
	
	public CachedLongImpl(LongAdapter origin) 
	{
		this.origin = origin;
	}

	@Override public void beginCalc(CalculationContext context)
	{
		cacheValues = context.getMapReduceFactory().map(origin);
	}
	
	@Override public void endCalc()
	{
		cacheValues = null;
	}
	
	@Override public PrepareAdapter prepare()
	{
		return this;
	}
	
	@Override public int size()
	{
		return cacheValues.length;
	}

	@Override public long getLong(int index)
	{
		return cacheValues[index];
	}

	@Override public NumericAdapter getParam(int index)	{
		return switchOf(index, origin);
	}

	@Override public FunctorInstance getFunctorInstance()
	{
		return DefaultFunctorInstances.ADAPTER.getFunctorInstance(
			DefaultFunctorInstances.FUNCTOR_STUB_ADAPTER, this, ValueType.LONG);
	}
}
